/**
 * 客户退货管理初始化
 */
var CustomerReturn = {
    id: "CustomerReturnTable",	//表格id
    customerReturnData:{},
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1
};

/**
 * 初始化表格的列
 */
CustomerReturn.initColumn = function () {
    return [
        {field: 'selectItem', radio: true},
            {title: '主键', field: 'id', visible: false, align: 'center', valign: 'middle'},
            {title: '实付金额', field: 'amountPaid', visible: true, align: 'center', valign: 'middle'},
            {title: '应付金额', field: 'amountPayable', visible: true, align: 'center', valign: 'middle'},
            {title: '客户退货单号', field: 'returnOrderNumber', visible: true, align: 'center', valign: 'middle'},
            {title: '是否支付', field: 'payState', visible: true, align: 'center', valign: 'middle'},
            {title: '创建者', field: 'createBy', visible: false, align: 'center', valign: 'middle'},
            {title: '创建时间', field: 'createDate', visible: true, align: 'center', valign: 'middle'},
            {title: '更新者', field: 'updateBy', visible: false, align: 'center', valign: 'middle'},
            {title: '更新时间', field: 'updateDate', visible: false, align: 'center', valign: 'middle'},
            {title: '备注信息', field: 'remarks', visible: true, align: 'center', valign: 'middle'},
            {title: '删除标记（0：正常；1：删除）', field: 'delFlag', visible: false, align: 'center', valign: 'middle'},
            {title: '客户id', field: 'customerId', visible: false, align: 'center', valign: 'middle'}
    ];
};

CustomerReturn.initGoodsColumns = function () {
    return [
        {title: '商品ID', field: 'goodsId', visible: false, align: 'center', valign: 'middle'},
        {title: '退货数量', field: 'returnGoodsNumber', visible: true, align: 'center', valign: 'middle'},
        {title: '商品编码', field: 'goodsCode', visible: true, align: 'center', valign: 'middle'},
        {title: '商品名称', field: 'goodsName', visible: true, align: 'center', valign: 'middle'},
        {title: '商品型号', field: 'goodsModel', visible: true, align: 'center', valign: 'middle'},
        {title: '商品单位', field: 'goodsUnit', visible: true, align: 'center', valign: 'middle'},
        {title: '商品单价', field: 'returnGoodsPrice', visible: true, align: 'center', valign: 'middle'},
        {title: '退货总价', field: 'totalPrice', visible: true, align: 'center', valign: 'middle'},
        {title: '库存数量', field: 'goodsInventoryQuantity', visible: true, align: 'center', valign: 'middle'},
        {title: '库存下限', field: 'goodsMinNum', visible: false, align: 'center', valign: 'middle'},
        {title: '上次采购价格', field: 'goodsLastPurchasePrice', visible: false, align: 'center', valign: 'middle'},
        {title: '创建者', field: 'createBy', visible: false, align: 'center', valign: 'middle'},
        {title: '创建时间', field: 'createDate', visible: false, align: 'center', valign: 'middle'},
        {title: '更新者', field: 'updateBy', visible: false, align: 'center', valign: 'middle'},
        {title: '更新时间', field: 'updateDate', visible: false, align: 'center', valign: 'middle'},
        {title: '备注信息', field: 'remarks', visible: false, align: 'center', valign: 'middle'},
        {title: '删除标记（0：正常；1：删除）', field: 'delFlag', visible: false, align: 'center', valign: 'middle'},
        {title: '供应商名称', field: 'supplierId', visible: false, align: 'center', valign: 'middle'},
        {title: '商品分类id', field: 'goodsCategoryId', visible: false, align: 'center', valign: 'middle'}
    ];
}


/**
 * 清除数据
 */
CustomerReturn.clearData = function () {
    this.goodsSaleData = {};
}
/**
 * 清除dom显示数据
 */
CustomerReturn.clearDom = function () {
    this
        .setDomVal('id')
        .setDomVal('amountPaid')
        .setDomVal('amountPayable')
        .setDomVal('saleOrderNumber')
        .setDomVal('payState')
        .setDomVal('createBy')
        .setDomVal('createDate')
        .setDomVal('updateBy')
        .setDomVal('updateDate')
        .setDomVal('remarks')
        .setDomVal('delFlag')
        .setDomVal('customerId');
}

/**
 * 收集数据
 */
CustomerReturn.collectData = function () {
    this
        .set('id')
        .set('amountPaid')
        .set('amountPayable')
        .set('saleOrderNumber')
        .set('customerId')
        .set('payState')
        .set('createBy')
        .set('createDate')
        .set('updateBy')
        .set('updateDate')
        .set('remarks')
        .set('delFlag');
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
CustomerReturn.set = function (key, val) {
    this.customerReturnData[key] = (typeof val === "undefined") ? $("#" + key).val() : val;
    return this;
}

/**
 * 设置dom中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
CustomerReturn.setDomVal = function (key, val) {
    (typeof val === "undefined") ? $("#" + key).val('') : $("#" + key).val(val);
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
CustomerReturn.get = function (key) {
    return $("#" + key).val();
}

/**
 * 检查是否选中
 */
CustomerReturn.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if(selected.length === 0){
        Feng.info("请先选中表格中的某一记录！");
        return false;
    }else{
        CustomerReturn.seItem = selected[0];
        return true;
    }
};

/**
 * 点击添加客户退货
 */
CustomerReturn.openAddCustomerReturn = function () {
    var index = layer.open({
        type: 2,
        title: '添加客户退货',
        area: ['800px', '420px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/customerReturn/customerReturn_add'
    });
    this.layerIndex = index;
};

/**
 * 打开查看客户退货详情
 */
CustomerReturn.openCustomerReturnDetail = function () {
    if (this.check()) {
        var index = layer.open({
            type: 2,
            title: '客户退货详情',
            area: ['800px', '420px'], //宽高
            fix: false, //不固定
            maxmin: true,
            content: Feng.ctxPath + '/customerReturn/customerReturn_update/' + CustomerReturn.seItem.id
        });
        this.layerIndex = index;
    }
};

/**
 * 选中商品后计算出价格并赋值
 */
CustomerReturn.calculateTotalPrice = function (cTotalPrice) {
    var cAmountPaid = $("#amountPaid").val();
    if (cAmountPaid === '') {
        $("#amountPaid").val(cTotalPrice);
    } else {
        var amountPaid = parseFloat(cAmountPaid);
        //累加价格
        $("#amountPaid").val(cTotalPrice + amountPaid);
    }
}


/**
 * 删除客户退货
 */
CustomerReturn.delete = function () {
    if (this.check()) {
        var selected = this.table.btInstance.bootstrapTable('getSelections');
        console.log(selected[0].goodsId);
        this.table.btInstance.bootstrapTable('removeByUniqueId', selected[0].goodsId);
    }
};

/**
 * 查询客户退货列表
 */
CustomerReturn.search = function () {
    var queryData = {};
    queryData['condition'] = $("#condition").val();
    CustomerReturn.table.refresh({query: queryData});
};

/**
 * 是否支付下拉框
 */
CustomerReturn.isPaySelect = function () {
    $("#payState").html("<option value='1'>已支付</option>" +
        "<option value='0'>未支付</option>")
}

/**
 * 查询客户
 */
CustomerReturn.selectCustomer = function () {
    //查找下游客户下拉框
    var ajax = new $ax(Feng.ctxPath + "/managerCustomer/list", function (data) {
        $.each(data, function (index, supplier) {
            var $customerId = $("#customerId");
            $customerId.empty();
            var customerId = supplier['id'];
            var customerName = supplier['customerName'];
            $customerId.html("<option value='" + customerId + "'>" + customerName + "</option>");
        })
    }, function (data) {
        Feng.error("获取供应商失败!" + data.responseJOSN.message + "!");
    });
    ajax.start();
}

/**
 * 保存前检查数据
 */
CustomerReturn.checkData = function () {
    var data = this.table.btInstance.bootstrapTable('getData', true);

    if ('' === data || typeof data === 'undefined' || data.length === 0) {
        Feng.info('请先添加商品!');
        return false;
    }

    var customer = $("#customerId option:selected").val();
    if ('' === customer || typeof customer === 'undefined') {
        Feng.info("请选择客户!");
        return false;
    }

    var amountPaid = $("#amountPaid").val();
    if ('' === amountPaid || typeof amountPaid === 'undefined') {
        Feng.info('请输入实付金额!');
        return false;
    }

    var createDate = $("#createDate").val();
    if('' === createDate || typeof createDate === 'undefined'){
        Feng.info("请选择销售日期!");
        return false;
    }

    var state = $("#payState option:selected").val();
    if ('' === state || typeof state === 'undefined') {
        Feng.info("请选择是否支付!");
        return false;
    }

    var returnSaleOrderNumber = $("#returnSaleOrderNumber").text();
    if ('' === returnSaleOrderNumber || typeof returnSaleOrderNumber === 'undefined') {
        Feng.info("订单号为空，请刷新页面重新提交!");
        return false;
    }

    return true;
}

/**
 * 保存销售订单
 */
CustomerReturn.save = function(){
    if (this.checkData()) {
        //清除数据
        this.clearData();
        //获取form数据
        this.collectData();
        var ajax = new $ax(Feng.ctxPath + "/customerReturn/add", function (data) {
            Feng.success(data.message);
            //清除表单
            CustomerReturn.clearData();
            //清除dom数据显示
            CustomerReturn.clearDom();
            //清除表格数据
            CustomerReturn.table.btInstance.bootstrapTable('removeAll');
            //输出
            console.log('新单号：', data.result);
            //重新赋值单号
            $("#returnSaleOrderNumber").text(data.result);
        }, function (data) {
            Feng.error("获取供应商失败!" + data.responseJOSN.message + "!");
        });
        //获取单据号码
        this.customerReturnData['returnOrderNumber'] = $('#returnSaleOrderNumber').text();
        //获取添加的表格数据
        this.customerReturnData['returnSaleGoodsList'] = this.table.btInstance.bootstrapTable('getData', true);
        //请求数据
        var requestData = JSON.stringify(this.customerReturnData);
        console.log("请求数据->", requestData);
        //设置为请求数据为json类型
        ajax.setContentType('application/json');
        ajax.setData(requestData);
        ajax.start();
    }
}



$(function () {
    var defaultColunms = CustomerReturn.initGoodsColumns();
    var table = new BSTable(CustomerReturn.id, "", defaultColunms);
    table.setShowRefresh(false);
    table.setShowColumns(false);
    table.setUniqueId("goodsId");
    table.setPaginationType("client");
    CustomerReturn.table = table.init();
    //是否支付下拉框
    CustomerReturn.isPaySelect();
    //查询下游客户
    CustomerReturn.selectCustomer();
});
